package mips.instructions;

/**
 * <code>SW</code> instruction<br/>
 * Store Word<br/>
 * @author jnmartin84@gmail.com
 */
public class SW extends Instruction {

	private static final String INSTRUCTION_NAME = "SW";
	private static final SW INSTANCE = new SW();

	private SW(){}

	public static final SW getInstance() {
		return INSTANCE;
	}

	/**
	 *
	 */
	@Override
	public final void execute(final int instruction) {
		
		final int rs = (instruction >> 21) & 0x0000001F;
		final int rt = (instruction >> 16) & 0x0000001F;
		final int immed = Instruction.signExtendH((instruction) & 0x0000FFFF);
		
		// double-check this works right!
		n64.MemoryManager.writeWord((int)(mips.R4300i.GPR[rt] & 0x00000000FFFFFFFFL), (int)(mips.R4300i.GPR[rs] & 0x00000000FFFFFFFFL) + immed);

		mips.R4300i.PC = mips.R4300i.nPC;
		mips.R4300i.nPC = mips.R4300i.PC + 4;
	}
	
	/**
	 * {@inheritDoc}
	 */
	@Override
	public final String emit(final int instruction) {
		
		final int rs = (instruction >> 21) & 0x0000001F;
		final int rt = (instruction >> 16) & 0x0000001F;
		final int immed = Instruction.signExtendH((instruction) & 0x0000FFFF);
		
		return	"		// double-check this works right!\n" +  
				"		n64.MemoryManager.writeWord((int)(mips.CPU.GPR["+rt+"] & 0x00000000FFFFFFFFL), (int)(mips.CPU.GPR["+rs+"] & 0x00000000FFFFFFFFL) + "+immed+");\n" + 
				"		\n" + 
				"		mips.CPU.PC = mips.CPU.nPC;\n" + 
				"		mips.CPU.nPC = mips.CPU.PC + 4;";
	}
	
	/**
	 * {@inheritDoc}
	 */
	@Override
	public final String getName(final int instruction) {
		return getName();
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public final String getName() {
		return INSTRUCTION_NAME;
	}
}